<template>
  <div class="">
    <form action="/">
      <van-search
        v-model="keywords"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        action-text="搜索"
        @cancel="onSearch"
      />
    </form>

    <h5>历史记录 <button @click="clear">清空</button></h5>
    <ul>
      <li v-for="(item, index) in history" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
import { Dialog } from "vant";
export default {
  data() {
    return {
      keywords: "",
      history: [],
    };
  },
  mounted() {
    if (localStorage.getItem("history")) {
      this.history = JSON.parse(localStorage.getItem("history"));
    }
  },
  methods: {
    onSearch() {
      //   console.log("sousuo ");
      if (this.history.length < 3) {
        this.history.unshift(this.keywords);
      } else {
        this.history.pop();
        this.history.unshift(this.keywords);
        //为了保证三条历史记录是最新的三条 删除尾部的最后一条 并往开头添加一条
      }

      localStorage.setItem("history", JSON.stringify(this.history));
      this.$router.push({ path: "/list", query: { keywords: this.keywords } });
    },
    clear() {
      Dialog.confirm({
        title: "删除",
        message: "是否清空",
      })
        .then(() => {
          // on confirm
          this.history = [];
          localStorage.removeItem("history");
        })
        .catch(() => {
          // on cancel
        });
    },
  },
  components: {},
};
</script>

<style lang="scss"></style>
